package com.cskaoyan.controller;


import com.cskaoyan.bean.CskaoyanmallStorage;
import com.cskaoyan.bean.Img;
import com.cskaoyan.bean.Storage;
import com.cskaoyan.service.BrandService;
import com.cskaoyan.service.CskaoyanmallStorageService;
import com.cskaoyan.utils.QiniuCloudUtil;
import com.cskaoyan.vo.BaseRespVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
public class AdminStorageController {

    @Autowired
    Img img;

    @Autowired
    CskaoyanmallStorageService cskaoyanmallStorageService;

    @Autowired
    BrandService brandService;

    //http://localhost:8083/admin/storage/create
    @RequestMapping("admin/storage/create")
    public BaseRespVo create(@RequestParam MultipartFile file){
        if (file.isEmpty()) {
            return BaseRespVo.erro(400,"文件不能为空");
        }
        try {
            String originalFilename = file.getOriginalFilename();
            long size = file.getSize();
            byte[] bytes = file.getBytes();
            String imageName = UUID.randomUUID().toString();
            try {
                //使用base64方式上传到七牛云
                String url = QiniuCloudUtil.put64image(bytes, imageName,originalFilename,size);
                String[] types = originalFilename.split("\\.");
                String type = types[1];
                CskaoyanmallStorage storage = new CskaoyanmallStorage();
                storage.setDeleted(false);
                storage.setKey(imageName);
                storage.setName(originalFilename);
                storage.setType(type);
                storage.setSize((int) size);
                storage.setUrl(url);
                cskaoyanmallStorageService.insertSelective(storage);
                img.setUrl(url);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            return BaseRespVo.erro(400,"上传图片异常");
        }
        return BaseRespVo.ok(img);
    }

    @RequestMapping("wx/storage/upload")
    public BaseRespVo update(@RequestParam MultipartFile file){
            Storage storage=brandService.storageUpload(file);
            return BaseRespVo.ok(storage);
    }


}
